package com.p2p.front.web.controller;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.p2p.base.annotation.LoginNeedless;
import com.p2p.base.cache.Cache;
import com.p2p.base.model.BaseUser;
import com.p2p.base.model.ValidateCodeSend.BizTypeEnum;
import com.p2p.base.model.ValidateCodeSend.SendSMSTypeEnum;
import com.p2p.base.util.BasePropertyConfigurer;
import com.p2p.base.util.DateUtil;
import com.p2p.base.util.Encrypter;
import com.p2p.base.util.LoginToken;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.model.User;
import com.p2p.front.service.MemberPointService;
import com.p2p.front.service.UserRegisterService;
import com.p2p.front.service.UserService;
import com.p2p.front.util.ValidateUtil;
import com.p2p.front.vo.UserCenterResult;
import com.p2p.front.vo.UserRegisterVo;
import com.p2p.front.web.form.RegisterForm;

/**
 * 用户注册相关信息
 * 
 * @author <a href="mailto:liyang@yiqihao.com">李阳</a>
 * @version 1.0
 */
@Controller
public class RegisterController extends BaseController {

	@Resource
	private UserRegisterService userRegisterService;

	@Resource
	private UserService userService;

	@Resource
	private Cache defaultCache;

	@Resource
	private MemberPointService memberPointService;

	@RequestMapping(value = "/authId", method = RequestMethod.GET)
	private String authID() {
		return "register/authentication";
	}

	@LoginNeedless
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register(Model model) {
		RegisterForm registerForm = new RegisterForm();
		model.addAttribute("registerForm", registerForm);
		return "register/register";
	}

	/**
	 * 
	 * @param emailAddres
	 * @param code
	 * @param type
	 *            0:注册时发送邮件；1:找回密码时发送邮件；2:邮箱认证时发送邮件 ；3:找回邮箱时发送邮件
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/sendEmail", method = RequestMethod.POST)
	public void sendEmail(@RequestParam("uemail") String emailAddres,
			@RequestParam(value = "code", required = false) String code,
			@RequestParam("type") int type, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		JSONObject jsonObj = new JSONObject();
		Boolean validateEmail = ValidateUtil.validateEmail(emailAddres);
		if (!validateEmail) {
			jsonObj.put("success", false);
			jsonObj.put("msg", "* 邮箱格式不正确 *");
			returnJsonObject(response, jsonObj);
			return;
		}
		String requestURL = request.getRequestURL().toString();
		UserCenterResult result = null;

		BaseUser u = getCurrentUser();
		model.addAttribute("baseUser", u);
		result = userRegisterService.sendEmail(emailAddres, code, type,
				requestURL.replace("/sendEmail.html", "/validateEmail/"),
				u==null?"null":u.getId());

		if (result.isSuccess()) {
			jsonObj.put("success", true);
			jsonObj.put("msg", "邮件发送成功");
		} else {
			jsonObj.put("success", false);
			jsonObj.put("msg", result.getMsgs().get(0));
		}
		// jsonObj.put("code", result);
		returnJsonObject(response, jsonObj);

		// if (result.isSuccess()) {
		// return "register/sendEmailSuccess";
		// } else {
		// model.addAttribute("errInfo", result.getMsgs().get(0));
		// if (type == SendEmailTypeEnum.TYPE_REGISTER.getIndex()) {
		// return "register/register";
		// } else if (type == SendEmailTypeEnum.TYPE_GETPWD.getIndex()) {
		// return "userInfo/forgetPwd";
		// } else if (type == SendEmailTypeEnum.TYPE_AUTH.getIndex()) {
		// return "userInfo/authInfo";
		// } else if (type == SendEmailTypeEnum.TYPE_OLDEMAIL.getIndex()) {
		// return "userInfo/modifyEmail";
		// } else {
		// return "404";
		// }
		// }

	}

	/**
	 * 手机发送验证码
	 * 
	 * @param mobileNum
	 * @param codeType
	 *            0:注册时候发送验证码 1:找回密码时发送验证码
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/sendIdentifyingCode", method = RequestMethod.POST)
	@LoginNeedless
	public void sendSMSCode(@RequestParam("mobile") String mobileNum,
			@RequestParam("codeType") int codeType, HttpServletRequest request,
			HttpServletResponse response) {

		JSONObject jsonObj = new JSONObject();
		Boolean validateMobile = ValidateUtil.isPhone(mobileNum);
		if (!validateMobile) {
			jsonObj.put("success", false);
			jsonObj.put("msg", "* 电话号码格式不正确 *");
			returnJsonObject(response, jsonObj);
			return;
		}
		UserCenterResult result = null;
		if (codeType == SendSMSTypeEnum.TYPE_REGISTER.getIndex()) {// 注册时生成验证码
			result = userRegisterService
					.sendSMSCode(mobileNum, "sendIdentifyingCode_",
							BizTypeEnum.MobileBinding, codeType);
		} else if (codeType == SendSMSTypeEnum.TYPE_GETPWD.getIndex()) {// 找回密码时生成验证码
			result = userRegisterService.sendSMSCode(mobileNum,
					"sendIdentifyingCodeForGetPwd_",
					BizTypeEnum.MobileBindingForGetPwd, codeType);
		} else if (codeType == SendSMSTypeEnum.TYPE_MODIFYPHONE.getIndex()) {// 修改手机时生成验证码
			result = userRegisterService.sendSMSCode(mobileNum,
					"sendIdentifyingCodeForModifyMobile_",
					BizTypeEnum.MobileBindingForModifyMobile, codeType);
		} else if (codeType == SendSMSTypeEnum.TYPE_MODIFYEMAIL.getIndex()) {// 修改邮箱时生成验证码
			result = userRegisterService.sendSMSCode(mobileNum,
					"sendIdentifyingCodeForModifyEmail_",
					BizTypeEnum.MobileBindingForModifyEmail, codeType);
		}
		
		if (result.isSuccess()) {
			jsonObj.put("success", true);
			jsonObj.put("code", result.getResultCode());
			jsonObj.put("msg", "验证码发送成功");
		} else {
			jsonObj.put("success", false);
			jsonObj.put("msg", result.getMsgs().get(0));
		}
		// jsonObj.put("code", result);
		returnJsonObject(response, jsonObj);
	}

	/** 邮箱发送验证码 **/
	@RequestMapping(value = "/sendCodeEmail", method = RequestMethod.POST)
	@LoginNeedless
	public void sendCodeEmail(@RequestParam("email") String email,
			@RequestParam("codeType") int codeType, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject jsonObj = new JSONObject();
		Boolean validateEmail = ValidateUtil.validateEmail(email);
		if (!validateEmail) {
			jsonObj.put("success", false);
			jsonObj.put("msg", "邮箱格式不正确 *");
			returnJsonObject(response, jsonObj);
			return;
		 }
		UserCenterResult result = null;
		 if (codeType == SendSMSTypeEnum.TYPE_MODIFYPHONE.getIndex()) {// 修改手机时生成验证码
			 result = userRegisterService.sendCodeByEmail(email,
						"sendIdentifyingCodeForModifyMobile_",
						BizTypeEnum.MailForModifyMobile, codeType);
			}else if(codeType == SendSMSTypeEnum.TYPE_REGISTER.getIndex()){
				result = userRegisterService.sendCodeByEmail(email,
						"sendIdentifyingCodeForModifyMobile_",
						BizTypeEnum.MailBinding, codeType);
			}else if(codeType == SendSMSTypeEnum.TYPE_MODIFYEMAIL.getIndex()){
				result = userRegisterService.sendCodeByEmail(email,
						"sendIdentifyingCodeForModifyMobile_",
						BizTypeEnum.MailForModifyEmail, codeType);
			}else if(codeType == SendSMSTypeEnum.TYPE_GETPWD.getIndex()){
				result = userRegisterService.sendCodeByEmail(email,
						"sendIdentifyingCodeForModifyMobile_",
						BizTypeEnum.MailBindingForGetPwd, codeType);
			}
		
			if (result.isSuccess()) {
				jsonObj.put("success", true);
				jsonObj.put("code", result.getResultCode());
				jsonObj.put("msg", "验证码发送成功");
			} else {
				jsonObj.put("success", false);
				jsonObj.put("msg", result.getMsgs().get(0));
			}
			returnJsonObject(response, jsonObj);
	}

	/**
	 * 手机注册保存
	 * 
	 * @author
	 * @param userRegisterVo
	 * @return
	 */
	@LoginNeedless
	@RequestMapping(value = "/saveResigterInfo", method = RequestMethod.POST)
	public String doRegisterByMobile(@Valid RegisterForm registerForm,
			Errors errors, int registerType, Model model) {
		if (errors.hasErrors()) {
			return "register/register";
		}
		
		Boolean validateMobile = ValidateUtil.isPhone(registerForm.getUmobile());
		if(!validateMobile){
			model.addAttribute("errInfo_exist", "手机号码格式不正确 *");
			model.addAttribute("registerForm", registerForm);
			return "register/register";
		}
		User user = userService.findByPhone(registerForm.getUmobile());
		if (user != null && user.getUmobile() != null) {
			model.addAttribute("errInfo_exist", "手机已经注册 *");
			model.addAttribute("registerForm", registerForm);
			return "register/register";
		}
		//注册的时候，不再需要用户名
		User unameUser=userService.findByUname(registerForm.getUname());
		if(unameUser != null && unameUser.getUname() != null){
			model.addAttribute("errInfo_uname_exist", "用户名已经存在");
			model.addAttribute("registerForm", registerForm);
			return "register/register";
		}
		
		// validate SMSCode
		UserCenterResult userCenterResult = userRegisterService.checkSMSCode(
				registerForm.getUmobile(), registerForm.getIdentifyingCode(),
				BizTypeEnum.MobileBinding);
		if (!userCenterResult.isSuccess()) {
			model.addAttribute("errInfo_code", "验证码不正确");
			model.addAttribute("registerForm", registerForm);
			return "register/register";
		}
		UserRegisterVo userRegisterVo = new UserRegisterVo();
		userRegisterVo.setUmobile(registerForm.getUmobile());
		userRegisterVo.setUname(registerForm.getUname());
		userRegisterVo.setPassword(registerForm.getPassword());
		userRegisterVo.setIdentifyingCode(registerForm.getIdentifyingCode());
		userRegisterVo.setRegisterType(registerType);
		userRegisterService.doRegisterByMobile(userRegisterVo);
		model.addAttribute("uid", userRegisterVo.getUid());

		//初始化用户积分
		memberPointService.getUserMemberPoint(userRegisterVo.getUid());
		String loginDomain = BasePropertyConfigurer.getContextProperty(
				"p2p.loginDomain").toString();
		String userHomeUrl = BasePropertyConfigurer.getContextProperty(
				"p2p.userDomain").toString()
				+ "/home/index.html";
		String tokenLoginUrl = loginDomain + "/tokenlogin.html?backUrl="
				+ userHomeUrl;
		String token = registerForm.getUmobile() + ","
				+ LoginToken.DEFAULT_SALT + ","
				+ DateUtil.getDateStr(new Date());
		String encrypedToken = Encrypter.encrypt(token);
		tokenLoginUrl += "&token=" + encrypedToken;
		return "redirect:" + tokenLoginUrl;
	}
	
	@LoginNeedless
	@RequestMapping("checkuname")
	public void checkUname(@RequestParam String uname,Model model){
		User user=userService.findByUname(uname);
		if(user != null){
			model.addAttribute("exist", 1);
		}else{
			model.addAttribute("exist", 0);
		}
	}
	
	@LoginNeedless
	@RequestMapping("checkmobile")
	public void checkMobile(@RequestParam String mobile,Model model){
		User user=userService.findByPhone(mobile);
		if(user != null){
			model.addAttribute("exist", 1);
		}else{
			model.addAttribute("exist", 0);
		}
	}
	
	@LoginNeedless
	@RequestMapping("privacy")
	public String  privacy(){
		return "register/privacy";
	}
	
	@LoginNeedless
	@RequestMapping("agreement")
	public String  agreement(){
		return "register/agreement";
	}
}
